//
//  LoginPwdViewController.m
//  DaDaBao
//
//  Created by admin on 15/8/18.
//  Copyright (c) 2015年 User. All rights reserved.
//

#import "LoginPwdViewController.h"
#import "CustomTextField.h"

@interface LoginPwdViewController ()<UITableViewDataSource,UITableViewDelegate,UIAlertViewDelegate>

@property(nonatomic,strong)UITableView *tableview;
@property(nonatomic,strong)NSArray *dataArr;
@property(nonatomic,strong)CustomTextField  *oldPwdText;
@property(nonatomic,strong)CustomTextField  *pwdText;
@property(nonatomic,strong)CustomTextField  *surePwdText;

@end

@implementation LoginPwdViewController
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloginView) name:@"reLogin" object:nil];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    [MBProgressHUD hideAllHUDsForView:self.view animated:TRUE];
}
-(void)reloginView
{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"登录失败，请重新登录" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
    [alert show];
}
#pragma mark ----------------alertDelegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    [AppGlobalClass exitLogin];
    
    LoginViewController *loginViewCon = [[LoginViewController alloc]init];
    [self presentViewController:loginViewCon animated:TRUE completion:^{}];
    
    NSArray *listArray = self.navigationController.viewControllers;
    
    id tabBar = [listArray objectAtIndex:1];
    if([[tabBar class] isSubclassOfClass:[UITabBarController class]])
    {
        UITabBarController *tabBarCon = tabBar;
        tabBarCon.selectedIndex = 0;
        [self.navigationController popToViewController:[listArray objectAtIndex:1] animated:TRUE];
    }
    else
    {
        UITabBarController *tabBarCon = [listArray objectAtIndex:2];
        tabBarCon.selectedIndex = 0;
        [self.navigationController popToViewController:[listArray objectAtIndex:2] animated:TRUE];
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor hexStringToColor:@"#ebebeb"];
       if (!_dataArr) {
        _dataArr = @[@"原登录密码",@"新登录密码",@"确认登录密码"];
    }
    [self createUI];

}
-(void)createUI
{
    TopView *topView =[[TopView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, SCREEN_WIDTH, 64.0f)];
    [topView setTitile:@"修改密码"];
    UIButton *backBtn = [[UIButton alloc]initWithFrame:CGRectMake(0.0f, 20.0f, 64.0f, 44.0f)];
    [backBtn setBackgroundImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(buttonBackTapped:) forControlEvents:UIControlEventTouchUpInside];
    [topView addSubview:backBtn];
    
    [self.view addSubview:topView];
    
    if (!_tableview) {
        _tableview = [[UITableView alloc] initWithFrame:CGRectMake(0.0f, 64.0f+35.0f, SCREEN_WIDTH, 44.0f*3) style:UITableViewStylePlain];
        _tableview.delegate = self;
        _tableview.dataSource = self;
        _tableview.bounces = FALSE;
        _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        [self.view addSubview:_tableview];
        
    }
    
//   修改登录密码按钮
    UIButton *checkBtn =  [UIButton buttonWithType:UIButtonTypeCustom];
    checkBtn.frame = CGRectMake(15.0f, _tableview.frame.origin.y+_tableview.frame.size.height+25.0f, SCREEN_WIDTH-30.0f, 35.0f*HSCALE);
    [checkBtn setBackgroundColor:[UIColor hexStringToColor:RED_COLOR_VALUE]];
    [checkBtn setTitle:@"修改登录密码" forState:UIControlStateNormal];
    checkBtn.layer.cornerRadius = 5.0f;
    [checkBtn addTarget:self action:@selector(buttonCheckTapped:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:checkBtn];


}
#pragma mark- tableViewDatasource &delegate

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        UILabel *sepLab = [[UILabel alloc] initWithFrame:CGRectMake(0.0f, 43.5f, SCREEN_WIDTH, 0.5f)];
        sepLab.backgroundColor = [UIColor lightGrayColor];
        [cell addSubview:sepLab];
        
        
    }
    cell.textLabel.text = [_dataArr objectAtIndex:indexPath.row];
    NSString *str = @"6-30位英文字母、数字或符号";
    switch (indexPath.row) {
        case 0:
        {
            _oldPwdText = [[CustomTextField alloc] initWithFrame:CGRectMake(110.0f, 13.0f, SCREEN_WIDTH-120.0f, 24.0f)];
            _oldPwdText.placeholder=str;
            _oldPwdText.secureTextEntry = TRUE;
            [_oldPwdText addTarget:self action:@selector(textFieldDidChanged:) forControlEvents:UIControlEventEditingChanged];
            [_oldPwdText setValue:[UIFont boldSystemFontOfSize:14.0f] forKeyPath:@"_placeholderLabel.font"];
            [cell addSubview:_oldPwdText];
        }
            break;
        case 1:
        {
            _pwdText = [[CustomTextField alloc] initWithFrame:CGRectMake(110.0f, 13.0f, SCREEN_WIDTH-120.0f, 24.0f)];
            _pwdText.placeholder = str;
            _pwdText.secureTextEntry = TRUE;
            [_pwdText addTarget:self action:@selector(textFieldDidChanged:) forControlEvents:UIControlEventEditingChanged];
            [_pwdText setValue:[UIFont boldSystemFontOfSize:14.0f] forKeyPath:@"_placeholderLabel.font"];

            [cell addSubview:_pwdText];
        }
            break;
        case 2:
        {
            _surePwdText = [[CustomTextField alloc] initWithFrame:CGRectMake(125.0f, 13.0f, SCREEN_WIDTH-135.0f, 24.0f)];
            _surePwdText.placeholder = str;
            _surePwdText.secureTextEntry = TRUE;
            [_surePwdText addTarget:self action:@selector(textFieldDidChanged:) forControlEvents:UIControlEventEditingChanged];
            [_surePwdText setValue:[UIFont boldSystemFontOfSize:14.0f] forKeyPath:@"_placeholderLabel.font"];

            [cell addSubview:_surePwdText];
            
        }
            break;
            
        default:
            break;
    }
    
    return cell;
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataArr.count;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}
#pragma mark- 提交审核方法
-(void)buttonCheckTapped:(id)sender
{
    [self.view endEditing:TRUE];
    
    //    1.   发送请求，提交审核
    
    //    2.判断新密码
    BOOL isPwdRight = [_oldPwdText checkNewLoginPwd:_oldPwdText.text];
    BOOL isSurePwd = [_surePwdText.text isEqualToString:_pwdText.text];
    BOOL isRight = [_pwdText checkNewLoginPwd:_pwdText.text];
    
    if(_oldPwdText.text.length<=0)
    {
        ALERT_VIEW(@"原密码不能为空");
        return;
    }
    if(_pwdText.text.length<=0)
    {
        ALERT_VIEW(@"新密码不能为空");
        return;
    }
    if(_surePwdText.text.length<=0)
    {
        ALERT_VIEW(@"确认密码不能为空");
        return;
    }
    
    if (isPwdRight == FALSE)
    {
        ALERT_VIEW(@"旧密码长度不合法");
        return;
    }
    if (isRight == FALSE)
    {
        ALERT_VIEW(@"新密码长度不合法");
        return;
    }
    if (isSurePwd == FALSE)
    {
        ALERT_VIEW(@"两次输入的密码不相同");
        return;
    }
    
    
    //   3.确认无误后返回上级页面
    [MBProgressHUD showHUDAddedTo:self.view animated:TRUE];

    NSDictionary *dict = @{ @"token":[[NSUserDefaults standardUserDefaults]objectForKey:@"token"], @"password":[AppGlobalClass md5:_surePwdText.text], @"oldPassword":[AppGlobalClass md5:_oldPwdText.text] };

    [AppGlobalClass PostDataWithNSstring:UPDATE_PASSWORD_URL withDictionary:dict success:^(NSDictionary *dictionary){
        if([[dictionary objectForKey:@"success"] isEqualToNumber:[NSNumber numberWithBool:TRUE]])
        {
            [[NSUserDefaults standardUserDefaults]setValue:[AppGlobalClass md5:_surePwdText.text] forKey:@"password"];
            ALERT_VIEW(@"修改密码成功");
            [self.navigationController popViewControllerAnimated:TRUE];
        }
        else
        {
            ALERT_VIEW([dictionary objectForKey:@"message"]);
        }
        [MBProgressHUD hideAllHUDsForView:self.view animated:TRUE];

    } failure:^(NSError *error){
        [MBProgressHUD hideAllHUDsForView:self.view animated:TRUE];
} networkerror:^(NSString *networkerror){
    [MBProgressHUD hideAllHUDsForView:self.view animated:TRUE];
}];
}
-(void)textFieldDidChanged:(UITextField *)textField
{
    if (textField.text.length>30)
    {
        ALERT_VIEW(@"密码长度不能超过30位");
        textField.text = [textField.text substringToIndex:30];
    }
}
#pragma mark-返回上一页
-(void)buttonBackTapped:(id)sender
{
    [self.navigationController popViewControllerAnimated:TRUE];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
